package com.roc.web.action.merinfo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.TermBean;
import com.roc.page.BaseAction;
import com.roc.pojo.EsmidinfoMerinfo;
import com.roc.pojo.EsmidinfoTmp;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.BcTranType;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.TerminalBrand;
import com.roc.util.constant.TerminalName;
import com.roc.util.constant.TerminalType;

/**
 * 商户批量导入
 * 
 * @author zx-think
 * 
 */
@Component
@Scope("prototype")
@Namespace("/merinfoImportNS")
public class MerinfoImportAction extends BaseAction {

	private Logger logger = LogManager.getLogger(MerinfoImportAction.class);

	private List<OrgBean> orgList = new ArrayList<OrgBean>();

	private File upload;

	private YjPosInfo posInfo;

	private String msg;
	
	private String orgCode;

	@Autowired
	IorgService orgService;
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	ITerminalService terminalService;

	@Action(value = "merinfoImportInit", results = { @Result(name = "success", location = "/pages/merinfo/merinfoImport.jsp") })
	public String merinfoImportInit() throws Exception {
		org();

		Map<String, String> brandMap = new TreeMap<String, String>();
		for (TerminalBrand b : TerminalBrand.values()) {
			brandMap.put(b.getCode(), b.getName());
		}

		Map<String, String> nameMap = new TreeMap<String, String>();
		for (TerminalName b : TerminalName.values()) {
			nameMap.put(b.getCode(), b.getName());
		}

		Map<String, String> typeMap = new TreeMap<String, String>();
		for (TerminalType b : TerminalType.values()) {
			typeMap.put(b.getCode(), b.getName());
		}

		getSession().setAttribute("brandMap", brandMap);
		getSession().setAttribute("nameMap", nameMap);
		getSession().setAttribute("typeMap", typeMap);

		return SUCCESS;
	}

	@Action(value = "merinfoImport", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(location = "/pages/merinfo/merinfoImport.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp") })
	public String merinfoImport() throws Exception {

		if (upload == null) {
			msg = "请选择文件";
			return SUCCESS;
		}

		try {
			org();
			excelImpl();
			addActionError("导入商户成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	// 查询机构
	public void org() throws Exception {
		Operators logingOperators = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		orgList = orgService.listOrgs(logingOperators);

	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public YjPosInfo getPosInfo() {
		return posInfo;
	}

	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	

	public String getOrgCode() {
		return orgCode;
	}

	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}

	public void excelImpl() throws Exception {

		Operators op = (Operators) ActionContext.getContext().getSession().get(
				Constant.SESSION_LOGIN_MERCHANT);

		// 构造 XSSFWorkbook 对象，strPath 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(upload.getPath());
		// 读取第一章表格内容
		XSSFSheet sheet = xwb.getSheetAt(0);
		// 定义 row、cell
		XSSFRow row;
		EsmidinfoTmp y = new EsmidinfoTmp();
		EsmidinfoMerinfo yd = new EsmidinfoMerinfo();
		// 循环输出表格中的内容
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			for (int j = row.getFirstCellNum(); j < 27; j++) {
				String cell = "";
				yd.setCardType("01");// 身份证
				y.setSettBackId("00000000");//结算银行代码
				y.setBelongBranch(orgCode);
				y.setMerinfos(yd);
				// 通过 row.getCell(j).toString() 获取单元格内容
				if (row.getCell(j) != null) {
					//cell = Constance.Null2EmptyTrim(row.getCell(j).toString());
					row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);//设置成字符格式原样读取
					cell = Constance.Null2EmptyTrim(row.getCell(j).getStringCellValue());
				}
				// 转换格式
				String errorMes = change2EsmidinfoTmp(y, cell, j);
				if(!"".equals(errorMes)){
					throw new Exception("导入商户失败,原因:第"+(i+1)+"行:"+errorMes);
				}
				// 保存数据

			}
			//merinfoService.insertMerinfo(y, op, new ArrayList<TermBean>(),MerchantStatus.S_12.getCode());
		}

	}

	/**
	 * 处理导入EXCEL的每一列
	 * @param y
	 * @param cell
	 * @param row
	 * @return
	 * @throws ServiceException
	 */
	public String change2EsmidinfoTmp(EsmidinfoTmp y, String cell, int row) throws ServiceException {

		String cellNew = cell;

		switch (row) {
		case 0:
			if("".equals(cellNew)){
				return "商户类型不能为空";
			}
			y.setMerKind(cellNew);
			break;
		case 1:
			if("".equals(cellNew)){
				return "商户名称不能为空";
			}
			y.setMerName(cellNew);
			break;
		case 2:
			if("".equals(cellNew)){
				return "营业名称不能为空";
			}
			y.setMerBrName(cellNew);
			break;
		case 3:
			if("".equals(cellNew) || cellNew.length()!=6 ){
				return "营业起始时间不能为空或者格式错误";
			}
			y.setEngName(cellNew);
			break;
		case 4:
			if("".equals(cellNew) || cellNew.length()!=6 ){
				return "营业终止时间不能为空或者格式错误";
			}
			y.setEngBrName(cellNew);
			break;
		case 5:
			if("".equals(cellNew)){
				return "所属地区不能为空";
			}
			y.getMerinfos().setAreaCode(cellNew);
			break;
		case 6:
			if ("".equals(cellNew)) {
				return "终端数不能为空";
			}
			y.getMerinfos().setTerNum(Integer.parseInt(cellNew));	
			break;
		case 7:
			if("".equals(cellNew)){
				return "MCC码不能为空";
			}
			y.setMcc(cellNew);
			break;
		case 8:
			if("".equals(cellNew)){
				return "结算周期不能为空";
			}
			y.getMerinfos().setCycleId(cellNew);
			break;
		case 9:
			//商户扣率类型
			if("".equals(cellNew)){
				return "商户扣率类型不能为空";
			}
			y.setCommMode(cellNew);
			break;
		case 10:
			if ("".equals(cellNew)) {
				return "商户扣率不能为空";
			}
			y.setCommRate(Double.valueOf(cellNew));	
			
			break;
		case 11:
			if ("".equals(cellNew)) {
				return "封顶手续费金额不能为空";
			}
				y.setCommAmt(Double.valueOf(cellNew));	
			
			break;
		case 12:
			//导入excel开户银行改为不读取excel
			/*if("".equals(cellNew)){
				return "开户银行不能为空";
			}*/
			y.setAccBack("");
			break;
		case 13:
			if("".equals(cellNew)){
				return "开户行账号不能为空";
			}
			y.setAccNo(cellNew);
			break;
		case 14:
			if("".equals(cellNew)){
				return "电话不能为空";
			}
			y.setTel(cellNew);
			break;
		case 15:
			if("".equals(cellNew)){
				return "业务联系人不能为空";
			}
			y.setInsertContact(cellNew);
			break;
		case 16:
			y.setZipCode(cellNew);
			break;
		case 17:
			if("".equals(cellNew)){
				return "法人名称不能为空";
			}
			y.getMerinfos().setPersonalName(cellNew);
			break;
		case 18:
			if("".equals(cellNew)){
				return "法人手机号不能为空";
			}
			y.getMerinfos().setPersonalPhone(cellNew);
			break;
		case 19:
			if("".equals(cellNew)){
				return "法人证件号不能为空";
			}
			y.getMerinfos().setCardNo(cellNew);
			break;
		case 20:
			if("".equals(cellNew)){
				return "营业执照号不能为空";
			}
			y.getMerinfos().setBusinessLicences(cellNew);
			break;
		case 21:
			if("".equals(cellNew)){
				return "税务登记证号不能为空";
			}
			y.getMerinfos().setTaxRegCer(cellNew);
			break;
		case 22:
			y.getMerinfos().setOrganizationCode(cellNew);
			break;
		case 23:
			y.getMerinfos().setBankLicense(cellNew);
			break;
		case 24:
			y.setFax(cellNew);
			break;
		case 25:
			y.setEmail(cellNew);
			break;
		case 26:
			if("".equals(cellNew)){
				return "地址不能为空";
			}
			y.setAddr(cellNew);
			break;	
		default:
			break;
		}

		return "";

	}
	
}
